#!/usr/bin/env python

import os, sys, glob

try:
	from os.path import relpath
except:
	def relpath(path, start=os.path.curdir):
	    """Return a relative version of a path"""

	    if not path:
		raise ValueError("no path specified")

	    start_list = os.path.abspath(start).split(os.path.sep)
	    path_list = os.path.abspath(path).split(os.path.sep)

	    # Work out how much of the filepath is shared by start and path.
	    i = len(os.path.commonprefix([start_list, path_list]))

	    rel_list = [os.path.pardir] * (len(start_list)-i) + path_list[i:]
	    if not rel_list:
		return os.path.curdir
	    return os.path.join(*rel_list)

if len(sys.argv) > 1:
	image = sys.argv[1]

if len(sys.argv) > 2:
	docpath = sys.argv[2] #os.path.dirname(sys.argv[2])
else:
	docpath = '.'

if len(sys.argv) > 3 and str.strip(sys.argv[3]):
	exts = map(str.strip, sys.argv[3].split(','))
else:
	# Standard images for web
	exts = ['png', 'svg', 'jpg', 'jpeg']

exts = map(lambda e: '.' + e, exts)

def lookup(image):
	images = glob.glob(os.path.join(docpath, image))
	if not images:
		return
	elif len(images) == 1:
		return images[0]

	found = map(lambda s: os.path.splitext(s)[1], images)
	for e in exts:
		if e not in found:
			continue
		return images[found.index(e)]
	else:
		return images[0]
i = lookup(image)
if not i:
	i = image
print relpath(i, docpath)
